package com.zhou.core.cmd;

import com.alibaba.fastjson.JSON;
import com.zhou.entitiy.ToolsResult;
import org.apache.commons.net.telnet.TelnetClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;


public class TelnetCmd {
    private static final Logger logger = LoggerFactory.getLogger(TelnetCmd.class);
    String host;
    int port;
    TelnetClient client;//telnet链接类
    PrintStream pw;//写流
    BufferedReader br;//读流
    String end_line ="please input command:";
    public TelnetCmd(String host, int port) {
        this.host = host;
        this.port = port;
    }
    public TelnetCmd(String host, int port, String endline) {
        this(host,port);
        this.end_line = endline.toLowerCase();
    }
    /**
     * 从服务器读取命令
     */
    public ToolsResult receiveMsgFromServer() {
        String line = null;
        try {
            List<String> list = new ArrayList<>();
            while ((line = br.readLine()) != null) {
                logger.info(toString()+"\tline="+line);
                if (line.trim().toLowerCase().contains(end_line)) {
                    break;
                }
                list.add(line);
            }
            return ToolsResult.createSuccResult(JSON.toJSONString(list));
        } catch (Exception e) {
            logger.error(toString()+"receiveMsgFromServer["+line+"] is error",e);
            return ToolsResult.RESULT_FAIL;
        }
    }

    /**
     * 向服务器写命令
     * @param cmd
     */
    public ToolsResult sendCmdToServer(CmdMsg cmd) {
        try {
            logger.info(toString()+"\t"+"telnet send cmd :" + cmd);
            pw.println(cmd.getCmd());
            pw.flush();
            return ToolsResult.createSuccResult("succ");
        } catch (Exception e) {
            logger.error(toString()+" sendCmdToServer["+cmd+"] is error...",e);
            return ToolsResult.createFailResult("fail");
        }
    }
    /**
     * 执行命令，包括发送和接受消息
     * @param cmd
     */
    public ToolsResult execCmd(CmdMsg cmd) {
        ToolsResult result = sendCmdToServer(cmd);
        if (!result.isSucc()) {
            return result;
        }
      return receiveMsgFromServer();
    }

    public void disconect() {
        try {
            if (pw != null) {
                pw.close();
            }
            if (pw != null) {
                br.close();
            }
            if (client != null) {
                client.disconnect();
            }
            pw = null;
            br = null;
            client = null;
        } catch (IOException e) {
            logger.error(toString() + " disconect is error...",e);
        }
    }

    public boolean connection() {
        client = new TelnetClient();
        try {
            logger.info(toString() + " telnet connect host["+host+"] port["+port+"] ....");
            client.connect(host, port);
            logger.info(toString() + "  telnet isConnected :" + client.isConnected());
            pw = new PrintStream(client.getOutputStream());
            br = new BufferedReader(new InputStreamReader(client.getInputStream(),"UTF-8"));
            return receiveMsgFromServer().isSucc();
        } catch (Exception e) {
            logger.error(toString() +" _connection is error...", e);
            return false;
        }
    }

    public boolean isConnect() {
        return client != null && client.isConnected();
    }
    public TelnetClient getClient() {
        return client;
    }
    public void setClient(TelnetClient client) {
        this.client = client;
    }
    public PrintStream getPw() {
        return pw;
    }
    public void setPw(PrintStream pw) {
        this.pw = pw;
    }
    public BufferedReader getBr() {
        return br;
    }
    public void setBr(BufferedReader br) {
        this.br = br;
    }

    public String toString() {
        return "TELNET["+host+","+port+"]";
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }



    public String getEnd_line() {
        return end_line;
    }

    public void setEnd_line(String end_line) {
        this.end_line = end_line;
    }

    public static void  main(String[] args)
    {
        TelnetCmd telnetCmd =  new TelnetCmd("52.8.73.147",24330);
        telnetCmd.connection();
        ToolsResult result = telnetCmd.execCmd(new CmdMsg("onlinerole",""));
        System.out.println(result.isSucc()+":"+result.getMsg());
        telnetCmd.disconect();
    }

}
